package qjc.h_二叉树;

import com.二叉树.练习题.TreeNode;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

public class h11_二叉树展开为链表 {
    /**
     * - 展开后的链表使用树的原有结构（right 指针作为 next，left 指向 null）
     * - 顺序为先序遍历：根 → 左 → 右
     * - 原地操作，不返回新树
     *
     * @param root
     */
    public void flatten(TreeNode root) {
        List<TreeNode> res = new ArrayList<>();
        Deque<TreeNode> stack = new LinkedList<>();
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                res.add(cur);
                cur = cur.left;
            }
            cur = stack.pop();
            cur = cur.right;
        }
        int size = res.size();
        for (int i = 1; i < size; i++) {
            TreeNode pre = res.get(i - 1);
            TreeNode next = res.get(i);
            pre.left = null;
            pre.right = next;
        }
    }
}
